<template>

	<scroll-view style="background-color: #f6f7f8;" class="flex-col page score-detail" scroll-y @scroll="onPageScroll">
		<view class="flex-col section" :style="{ paddingTop: '87' + 'px' }">
			<xlm-top-nav :scrollTop="scrollTop" title="成绩详情" />
			<scroll-view scroll-y class="scroll-view-content">
				<view class="score-detail-page">
					<!-- 顶部轮播图 -->
					<view class="banner-section">
						<swiper class="banner" :indicator-dots="true" :autoplay="true" :interval="3000"
							:circular="true">
							<swiper-item v-for="(item, index) in bannerList" :key="index">
								<view class="banner-content" @click="handleBannerClick(item)">
									<image v-if="item.thumb" :src="item.thumb" class="banner-image" />
								</view>
							</swiper-item>
						</swiper>
						<!-- 						<view class="banner-overlay">
							<view class="banner-title">{{ '' }}</view>
							<view class="banner-subtitle"></view>
							<picker mode="selector" :range="groupLabels" @change="onGroupChange" class="group-picker">
								<view class="banner-button">
									<text>{{ groupLabels[selectedGroupIndex] || '全部组别' }}</text>
									<text class="arrow">›</text>
								</view>
							</picker>
						</view> -->
					</view>

					<!-- 项目筛选标签 -->
					<!-- 				<view class="filter-section">
						<view class="filter-tabs">
							<view v-for="(item, index) in filterTabs" :key="index" class="filter-tab"
								:class="{ active: currentFilter === index }" @click="changeFilter(item, index)">
								{{ item.item_name }}
							</view>
						</view>
					</view> -->
					<!-- 筛选项必填 -->
					<view class="filterContain">


						<view class="filterContainItem">
							<view class="filterContainItemLeft">
								<text>背号</text>
							</view>
							<view class="filterContainItemRight">
								<input class="" type="text" v-model="from.num" placeholder="搜索背号" />
							</view>
						</view>
						<view class="cxBtn">
							<view class="" @click="getScoreList()">查询</view>
						</view>
						<!-- <view class="filterContainItem">
							<view class="filterContainItemLeft">
								<text>身份证号</text>
							</view>
							<view class="filterContainItemRight">
								<input class="" type="text" v-model="from.idcard" placeholder="搜索身份证号" />
							</view>
						</view> -->
						<!-- <view class="cxBtn">
							<view class="" style="opacity: 0;">展位</view>
							<view class="" style="opacity: 0;">展位</view>
							<view class="" @click="getScoreList()">查询</view>
						</view> -->
					</view>
					<!-- <view class="" style="height: 60rpx;"></view> -->
					<!-- 成绩列表头部 -->
					<view class="rackContain">
						<view class="list-header">
							<view class="header-item rank">排行</view>
							<view class="header-item athlete">运动员</view>
							<view class="header-item event">项目</view>
							<view class="header-item score">成绩</view>
							<view class="header-item wind">风速</view>
						</view>

						<!-- 成绩列表 -->
						<view class="score-list">
							<view class="" v-for="(item, index) in scoreList" :key="index">
								<view class="score-item">
									<view class="rank-section">
										<view class="rank-number">
											{{ item?.rank }}
										</view>
										<!-- <image v-if="item?.rank <= 3" class="medal-icon" :src="getMedalIcon(item?.rank)" />
														<text v-else class="rank-number">{{ item?.rank }}</text> -->
										<!-- <view v-if="index < 3" class="medal-icon" :class="`medal-${index + 1}`">
									  <text class="medal-number">{{ index + 1 }}</text>
									</view>
									<text v-else class="rank-number">{{ index + 1 }}</text> -->
									</view>

									<!-- 运动员信息 -->
									<view class="athlete-section">
										<image :src="item?.avatar ? item?.avatar : imgUrl + 'avatar1@2x.png'"
											class="athlete-avatar" />
										<view class="athlete-info">
											<view class="athlete-name">
												<text>{{ item?.username ? item?.username : '--' }}</text>
												<text>{{item.stage=='heat'?'预赛':'决赛'}}</text>
											</view>
											<view class="athlete-detail">
												<!-- {{ item.country }}  -->
												<!-- {{ item?.address ? item?.address : '--' }} -->
												背号:{{item?.num||'--'}}
											</view>

										</view>
									</view>

									<!-- 项目 -->
									<view class="event-section">
										<text class="event-name">{{ item?.item_name }}</text>
									</view>

									<!-- 成绩 -->
									<view class="score-section">
										<view class="score-time">{{ item?.score }}</view>
										<!-- <view class="pb-tag">{{item?.tag}}</view> -->
									</view>

									<!-- 风速 -->
									<view class="wind-section">
										<text class="wind-speed">{{ item?.wind || '-' }}</text>
									</view>
									<!-- 排行 -->
								</view>
								<view class="cjxp" @click="viewAthleteDetail(item)">成绩上屏</view>
								<view class="" style="height: 24rpx;"></view>
							</view>
						</view>

					</view>

					<!-- 加载更多 -->
					<!-- <view v-if="hasMore" class="load-more" @click="loadMore">
            <text>加载更多</text>
          </view> -->
				</view>
			</scroll-view>
		</view>
	</scroll-view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		useOutsideAppStore
	} from '@/store/app'
	import {
		imgUrl
	} from '@/utils/config'
	import {
		useRequest
	} from '@/api'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		log
	} from 'util'

	const {
		API_EVENT_ITEMS_POST,
		API_SCORE_DETAIL_POST,
		API_EVENT_GROUP_POST,
		API_SCORE_ADDCASTING_POST
	} = useRequest()

	let from = ref({
		username: '',
		mobile: '',
		idcard: '',
		num: '' //背号
	})

	const appStore = useOutsideAppStore()
	const navHeight = computed(() => appStore.navHeight)
	const scrollTop = ref(0)

	const onPageScroll = (e) => {
		scrollTop.value = e.detail.scrollTop
	}

	function getMedalIcon(rank) {
		const icons = {
			1: imgUrl + 'firstPlace@2x.png',
			2: imgUrl + 'runner-up@2x.png',
			3: imgUrl + 'thirdPlace@2x.png'
		}
		return icons[rank]
	}
	// 轮播图数据
	const bannerList = ref([{
		id: 1,
		thumb: imgUrl + 'a.jpg',
		title: '草源体育公开赛',
		link: 'http://example.com'
	}])

	// 筛选标签
	const filterTabs = ref()
	const currentFilter = ref(0)

	// 成绩列表数据
	const scoreList = ref([])

	const hasMore = ref(true)
	const loading = ref(false)
	const eventId = ref('')
	const item_id = ref('')
	const eventTitle = ref('')
	const groupList = ref([])
	const groupId = ref('')
	// 组别下拉
	const selectedGroupIndex = ref(0)
	const groupLabels = computed(() => {
		return (groupList.value || []).map((g, idx) =>
			g?.group_name || g?.name || g?.title || g?.item_name || g?.label || `组别${idx + 1}`
		)
	})
	onShow(() => {
		const pages = getCurrentPages() // 获取当前页面栈
		const currentPage = pages[pages.length - 1] // 获取当前页面
		console.log('currentPage', currentPage)

		const options = currentPage.options // 获取当前页面的参数
		const {
			event_id
		} = options
		// if (event_id) {
		//   eventId.value = event_id
		//   getEventItems(event_id)
		// }
	})

	onMounted(() => {
		// getBannerList()
		// getScoreList()
	})

	// 获取轮播图数据
	const getBannerList = async () => {
		try {
			const res = await API_SCORE_DETAIL_POST()
			if (res.code === 1 && res.data) {
				bannerList.value = res.data
			}
		} catch (error) {
			console.error('获取轮播图失败', error)
		}
	}
	const getEventItems = async (group_id) => {
		let params = {
			event_id: eventId.value,
			group_id
		}
		filterTabs.value = []
		item_id.value = ''
		try {
			const res = await API_EVENT_ITEMS_POST(params)
			console.log('getEventItems', res)

			if (res.code === 1) {
				// if (res.data.data.length > 0) {
				// 	filterTabs.value = res.data.data
				// 	if (filterTabs.value.length > 0) {
				// 		item_id.value = filterTabs.value[0].item_id
				// 		getEventGroup()
				// 		// getScoreList()
				// 	}
				// } else {
				// 	filterTabs.value = []
				// }
				filterTabs.value = res.data.data
				item_id.value = res.data.data[0].item_id // 项目id
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
			console.log('filterTabs', filterTabs.value)
		} catch (error) {
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		}
	}
	// 获取成绩列表
	const getScoreList = async () => {
		// return
		if (loading.value) return
		const {
			username,
			mobile,
			idcard,
			num
		} = from.value
		// if (!username && !mobile && !idcard && !num) {
		// 	uni.showToast({
		// 		title: '请至少输入一个搜索条件',
		// 		icon: 'none'
		// 	})
		// 	return
		// }
		if (!num) {
			uni.showToast({
				title: '请输入背号',
				icon: 'none'
			})
			return
		}
		const params = {
			event_id: eventId.value,
			username,
			mobile,
			idcard,
			num
			// item_id: item_id.value,
			// group_id: groupId.value
		}
		scoreList.value = []
		loading.value = true
		try {
			const res = await API_SCORE_DETAIL_POST(params)
			console.log('getScoreList', res)

			// if (res.code === 1) {
			// 	scoreList.value = res.data || []
			// 	console.log('scoreList+++++++', scoreList.value)
			// 	// hasMore.value = res.data.hasMore || false
			// } else {
			// 	uni.showToast({
			// 		title: res.msg,
			// 		icon: 'none'
			// 	})
			// }
			scoreList.value = res.data.data
		} catch (error) {
			console.error('获取成绩列表失败', error)
			uni.showToast({
				title: '获取数据失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 切换筛选标签
	const changeFilter = (item, index) => {
		// if (currentFilter.value === index) return
		item_id.value = item.item_id
		currentFilter.value = index
		getScoreList()
		// getEventGroup()
	}

	// 轮播图点击
	const handleBannerClick = (item) => {
		if (item.link) {
			uni.navigateTo({
				url: `/pages/webview/index?url=${encodeURIComponent(item.link)}&title=${encodeURIComponent(item.title)}`
			})
		}
	}

	// 显示全部组别
	const showAllCategories = () => {
		uni.showActionSheet({
			itemList: filterTabs.value,
			success: (res) => {
				changeFilter(res.tapIndex)
			}
		})
	}

	// 查看运动员详情 - 成绩上屏
	const viewAthleteDetail = async (athlete) => {
		// 判断运动员是否有成绩
		if (!athlete.score || athlete.score === '-' || athlete.score === '') {
			uni.showToast({
				title: '您暂时没有成绩',
				icon: 'none'
			})
			return
		}

		// 成绩上屏
		try {
			const res = await API_SCORE_ADDCASTING_POST({
				course_id: athlete.id
			})

			if (res.code === 1) {
				let seconds = res.data.time

				uni.showToast({
					title: getCountdownText(seconds),
					icon: 'none',
					duration: 4000
				})
			} else {
				uni.showToast({
					title: res.msg || '上屏失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('成绩上屏失败', error)
			uni.showToast({
				title: '上屏失败',
				icon: 'none'
			})
		}
	}
	const getCountdownText = (seconds) => {
		if (seconds < 60) {
			// 小于60秒，显示大约还需要多少秒
			return `大约还需要${Math.ceil(seconds)}秒成绩上屏`;
		} else {
			// 大于等于60秒，转换为分钟并显示
			const minutes = Math.ceil(seconds / 60);
			return `大约需要${minutes}分钟成绩上屏`;
		}
	}
	const getEventGroup = async () => {
		const params = {
			page: 1,
			page_size: 1000,
			event_id: eventId.value,
			// item_id: item_id.value
		}
		// groupList.value = []
		try {
			const res = await API_EVENT_GROUP_POST(params)
			if (res.code === 1) {
				// groupList.value = res.data.data || [];
				// // if (groupList.value.length > 0) {
				// selectedGroupIndex.value = 0
				// groupId.value = groupList?.value?.[0]?.group_id || ''
				// getScoreList()
				// // }
				groupList.value = res.data.data
				groupId.value = groupList?.value?.[0]?.group_id
				await getEventItems(res.data.data[0].group_id)
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		} catch (error) {
			uni.showToast({
				title: error.message,
				icon: 'none'
			})
		}
	}
	// 下拉选择组别
	const onGroupChange = async (e) => {
		console.log('下拉选择组别-----', e);
		groupId.value = groupList?.value?.[e.detail.value]?.group_id
		// let info = groupList?.value?.[e.detail.value]
		// console.log('下拉选择组别-----info',info);
		await getEventItems(groupList?.value?.[e.detail.value]?.group_id)
		await getScoreList()
		// const idx = Number(e?.detail?.value ?? 0)
		// selectedGroupIndex.value = idx
		// const target = groupList.value[idx]
		// groupId.value = target?.group_id || ''
		// getScoreList()
	}
	// 加载更多
	const loadMore = () => {
		if (!hasMore.value || loading.value) return
		getScoreList()
	}

	onLoad(async (options) => {
		eventId.value = options.event_id
		// await getEventGroup()
		// await getScoreList()
	})
	// onLoad((options) => {
	// 	eventId.value = options.event_id
	// 	getEventGroup()
	// 	setTimeout(() => {
	// 		getScoreList()
	// 	}, 300)
	// })
</script>



<style lang="scss">
	@import './index.scss';

	page {
		background-color: #f6f7f8;
	}

	.filterContain {
		margin: 24rpx;
		// margin-bottom: 50rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #ffffff;
		border-radius: 20rpx;
		padding: 10rpx 24rpx;
		box-sizing: border-box;

		.cxBtn {
			width: 96rpx;
			height: 64rpx;
			border: 2rpx solid #e5e5e5;
			border-radius: 8rpx;
			font-size: 26rpx;
			font-family: PingFang SC, PingFang SC-Regular;
			font-weight: 400;
			text-align: center;
			color: #121212;
			line-height: 64rpx;
			letter-spacing: 0.16rpx;
			// bottom: -10rpx;
		}

		.filterContainItem {
			display: flex;
			align-items: center;
			background: #ffffff;
			border-radius: 20rpx;
			// justify-content: space-between;

			.filterContainItemLeft {
				// width: 100rpx;
				margin-right: 16rpx;
				font-size: 26rpx;
				font-family: PingFang SC, PingFang SC-Medium;
				font-weight: bold;
				color: #121212;
			}

			.filterContainItemRight {
				width: 474rpx;
				height: 64rpx;
				background: #ffffff;
				border: 2rpx solid #e5e5e5;
				border-radius: 8rpx;

				input {
					width: 100%;
					height: 100%;
					padding: 0 24rpx;
					box-sizing: border-box;

				}


			}
		}
	}

	.rackContain {
		background: #ffffff;
		border-radius: 20rpx;
		margin: 0 24rpx;
		border-radius: 20rpx;
	}
</style>